package com.efivestar.idm.api.config.filter;

import com.efivestar.idm.api.util.weixin.ContextHolder;
import com.efivestar.idm.api.util.weixin.bean.WeiXinUser;
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
@Order(2)
@WebFilter(filterName = "userInfoValidateFilter", urlPatterns = "/*")
public class UserInfoValidateFilter implements Filter {

    Logger logger = LoggerFactory.getLogger(UserInfoValidateFilter.class);



    @Autowired
    private Environment env;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        WeiXinUser weixinUser = ContextHolder.getWeixinUser();
        if (weixinUser != null && !StringUtils.isEmpty(weixinUser.getOpenId()) && !StringUtils.isEmpty(weixinUser.getSignature())) {
            if (!validateSignature(weixinUser)) {
                logger.error("校验openId失败");
                return;
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    /**
     * 校验OpenId和签名是否是合法的.
     * @param weiXinUser
     * @return
     */
    private boolean validateSignature(WeiXinUser weiXinUser){
        String signatureKey = env.getProperty("openId.signature-key");
        String actualSignature = DigestUtils.md5Hex(weiXinUser.getOpenId() + signatureKey);
        String passedSignature = weiXinUser.getSignature();
        if (actualSignature.equals(passedSignature)) {
            return true;
        }
        return  false;
    }

    private String getRequestPath(HttpServletRequest request) {
        String url = request.getServletPath();
        if (request.getPathInfo() != null) {
            url += request.getPathInfo();
        }
        return url;
    }

    @Override
    public void destroy() {

    }

}